from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.db.database import get_db
from app.models.user import User
from app.schemas.auth_schema import Token, Login_Token
from app.schemas.user_schema import UserCreate,UserLogin
from app.utils.jwt import hash_password, verify_password, create_access_token,decode_access_token

router = APIRouter()

@router.post("/register", response_model=Token)
def register_user(user: UserCreate, db: Session = Depends(get_db)):
    db_user = db.query(User).filter(User.username == user.username).first()
    if db_user:
        raise HTTPException(status_code=400, detail="Email already registered")
    hashed_pwd = hash_password(user.password)
    new_user = User(username=user.username,phone=user.phone, email=user.email, password=hashed_pwd)
    db.add(new_user)
    db.commit()
    db.refresh(new_user)
    access_token = create_access_token(data={"sub": new_user.username})
    return {"access_token": access_token, "token_type": "bearer"}

@router.post("/login", response_model=Login_Token)
def login(user_data: UserLogin, db: Session = Depends(get_db)):
    user2 = db.query(User).filter(User.username == user_data.username).first()
    if not user2 or not verify_password(user_data.password, user2.password):
        raise HTTPException(status_code=401, detail="Invalid credentials")
    access_token = create_access_token(data={"sub": user2.username})
    return {"code":"200","msg":"登陆成功","access_token": access_token, "token_type": "bearer"}

@router.get("/decToken")
def decToken():
    m = decode_access_token("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0ZXN0dXNlcjkiLCJleHAiOjE3MzU0NjQyODZ9.rsUjaGlJoPgkxGzBp3rQznciekwKxsCn_qhg9xDcs")
    if m:
        return {"code":"200","msg":"解析成功","data":m}
    else:
        return {"code": "200", "msg": "令牌过期"}